package com.jhd.fuzhou.view.quantitative;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.view.login.FuzhouApplication;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.GradeReportService;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.TextDialog;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.vo.GradeQuestionBankVo;
import com.jhd.fuzhou.vo.GradeQuestionOptionVo;
import com.jhd.fuzhou.vo.JsonForResult;

import net.zigin.commons.util.StringUtil;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.jhd.fuzhou.view.login.MainActivity.supervisionInspectionVo;

public class QuantitativeStepThreeActivity extends BaseActivity {

    private Context context=this;
    private List<GradeQuestionBankVo> gradeQuestionBankVoList;//问题列表
    @BindView(R.id.rv_question_tree)RecyclerView rv_question_tree;
    private ProgressDialog _dialog;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_quantitative_step_three);
    }

    @Override
    protected void processLogic() {
        application.addStepActivity(this);
        onBack();
        if(supervisionInspectionVo.getGradeReportResultVoList()!=null){
            gradeQuestionBankVoList=supervisionInspectionVo.getGradeQuestionBankVoList();
            setQuestion();
        }else{
            getGradeQuestionBankList();
        }
    }

    private void setQuestion(){
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        rv_question_tree.setLayoutManager(layoutManager);
        QuestionTreeAdapter adapter=new QuestionTreeAdapter();
        rv_question_tree.setAdapter(adapter);
        /*下面将打分和选项先全部默认一下*/
        for (GradeQuestionBankVo gradeQuestionBankVo : gradeQuestionBankVoList) {
            if(gradeQuestionBankVo.getLevel()==3) {
                if(gradeQuestionBankVo.getActualScore()==-1){
                    gradeQuestionBankVo.setActualScore(0);
                }
                List<GradeQuestionOptionVo> gradeQuestionOptionVos = gradeQuestionBankVo.getGradeQuestionOptionVoList();
                if (StringUtil.isNullOrEmpty(gradeQuestionBankVo.getBankOptionId())) {
                    for (GradeQuestionOptionVo gradeQuestionOptionVo : gradeQuestionOptionVos) {
                        if ("1".equals(gradeQuestionOptionVo.getDefaultItem())) {
                            gradeQuestionBankVo.setBankOptionId(gradeQuestionOptionVo.getId());//选项的id，根据这个值判断是否已经选择选项
                            setIsFaultiness(gradeQuestionBankVo, gradeQuestionOptionVo);
                        }
                    }
                } else {
                    for (GradeQuestionOptionVo gradeQuestionOptionVo : gradeQuestionOptionVos) {
                        if (gradeQuestionBankVo.getBankOptionId().equals(gradeQuestionOptionVo.getId())) {
                            gradeQuestionBankVo.setBankOptionId(gradeQuestionOptionVo.getId());//选项的id，根据这个值判断是否已经选择选项
                            setIsFaultiness(gradeQuestionBankVo, gradeQuestionOptionVo);
                        }
                    }
                }
            }
        }
    }
    @OnClick({R.id.btn_next,R.id.btn_back})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.btn_next:
                String isFinish=isFinish();
                if(isFinish.equals("")){//可以评级
                    supervisionInspectionVo.setGradeQuestionBankVoList(gradeQuestionBankVoList);
                    startActivity(new Intent(context,QuantitativeStepFourActivity.class));
                }else{
                    CustomToast.showText(context,isFinish, 3000, 0, 0).show();
                }
                break;
            case R.id.btn_back:
                onBackPressed();
                break;
        }
    }

    private String isFinish(){
        String v=JSON.toJSONString(gradeQuestionBankVoList);
        for(int i=0;i<gradeQuestionBankVoList.size();i++){
            if(gradeQuestionBankVoList.get(i).getLevel()==3){
                String position=""+i;
                if (StringUtil.isNullOrEmpty(gradeQuestionBankVoList.get(i).getBankOptionId())) {
                    return "有未选择答案的检查项!";
                }else if ("0".equals(gradeQuestionBankVoList.get(i).getIsCrux())&&gradeQuestionBankVoList.get(i).getActualScore()==-1) {
                    return "有未评分的检查项,无法评级!";
                }
            }
        }
        return "";
    }

    private void getGradeQuestionBankList(){
        _dialog = new ProgressDialog(context);
        _dialog.setCanceledOnTouchOutside(false);
        _dialog.setMessage("正在生成量化分级评分表,请稍等...");
        _dialog.show();
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        GradeReportService vs = retrofit.create(GradeReportService.class);
        Map<String, String> params =  new LinkedHashMap<String, String>();
        params.put("specialityCategoryId", supervisionInspectionVo.getSpecialityCategoryId());
        params.put("detailCategoryName",supervisionInspectionVo.getSpecialityDetail());
        Call<JsonForResult> jsonForResultCall = vs.getGradeQuestionBankList(application.getAccessToken(),params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    _dialog.dismiss();
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            gradeQuestionBankVoList= JSON.parseArray(jsonForResult.getData().toString(), GradeQuestionBankVo.class);
                            setQuestion();
                        }else{
                            UtilHelper.alertMsg2(context, "错误", "该专业没有添加检查项目！");//关闭弹窗退出当前页面
                        }
                    } else {
                        CustomToast.showText(context, jsonForResult.getMessage(), 3000, 0, 0).show();
                    }
                } catch (Exception e) {
                    _dialog.dismiss();
                    UtilHelper.alertMsg(context, "错误", e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                _dialog.dismiss();
                String msg = "网络异常!";
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    public class QuestionTreeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder viewHolder = getViewHolderByViewType(viewType);
            return viewHolder;
        }

        private RecyclerView.ViewHolder getViewHolderByViewType(int viewType) {
            View itemLevel_1 = View.inflate(context,R.layout.item_quantitative_question_tree,null);
            View itemLevel_2 = View.inflate(context,R.layout.item_quantitative_question_tree_2, null);
            View itemLevel_3 = View.inflate(context,R.layout.item_quantitative_question_tree_3, null);
            RecyclerView.ViewHolder holder=null;
            switch (viewType){
                case 1:
                    holder=new QuestionTreeAdapter.ViewHolder1(itemLevel_1);
                    break;
                case 2:
                    holder=new QuestionTreeAdapter.ViewHolder2(itemLevel_2);
                    break;
                case 3:
                    holder=new QuestionTreeAdapter.ViewHolder3(itemLevel_3);
                    break;
            }
            return holder;
        }

        @Override
        public int getItemViewType(int position) {
            return gradeQuestionBankVoList.get(position).getLevel();
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            if(getItemViewType(position)==1){
                ((QuestionTreeAdapter.ViewHolder1)holder).tv_question.setText(gradeQuestionBankVoList.get(position).getQuestionName());
            }else if(getItemViewType(position)==2){
                ((QuestionTreeAdapter.ViewHolder2)holder).tv_question.setText(gradeQuestionBankVoList.get(position).getQuestionName());
            }else if(getItemViewType(position)==3){
                ((QuestionTreeAdapter.ViewHolder3)holder).tv_question.setText(gradeQuestionBankVoList.get(position).getQuestionName());
                ((QuestionTreeAdapter.ViewHolder3)holder).et_score.setHint("应扣分"+gradeQuestionBankVoList.get(position).getScore()+"分");
                ((QuestionTreeAdapter.ViewHolder3)holder).et_score.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TextDialog.showScore(context,((QuestionTreeAdapter.ViewHolder3)holder).et_score,gradeQuestionBankVoList.get(position));
                    }
                });
                if("1".equals(gradeQuestionBankVoList.get(position).getIsCrux())){//为重要项，不计分
                    ((ViewHolder3)holder).tv_important.setVisibility(View.VISIBLE);
                    ((ViewHolder3)holder).lin_score.setVisibility(View.GONE);
                }else{
                    ((ViewHolder3)holder).tv_important.setVisibility(View.GONE);
                    ((ViewHolder3)holder).lin_score.setVisibility(View.VISIBLE);
                    ((QuestionTreeAdapter.ViewHolder3)holder).et_score.setText(""+((gradeQuestionBankVoList.get(position).getActualScore()==-1)?gradeQuestionBankVoList.get(position).getScore():gradeQuestionBankVoList.get(position).getActualScore()));//目前默认都是合格和最高分
                }
                List<GradeQuestionOptionVo> gradeQuestionOptionVoList=gradeQuestionBankVoList.get(position).getGradeQuestionOptionVoList();
                if(gradeQuestionOptionVoList!=null) {
                    GridLayoutManager layoutManager = new GridLayoutManager(context, 3);
                    ((ViewHolder3)holder).rv_answer.setLayoutManager(layoutManager);
                    ChoiceAdapter adapter = new ChoiceAdapter(gradeQuestionBankVoList.get(position),gradeQuestionOptionVoList,((QuestionTreeAdapter.ViewHolder3)holder).et_score);
                    ((ViewHolder3)holder).rv_answer.setAdapter(adapter);
                }
            }
        }

        @Override
        public int getItemCount() {
            return gradeQuestionBankVoList.size();
        }

        public class ViewHolder1 extends RecyclerView.ViewHolder {
            TextView tv_question;
            public ViewHolder1(View itemView) {
                super(itemView);
                tv_question = (TextView) itemView.findViewById(R.id.tv_question);
            }
        }
        public class ViewHolder2 extends RecyclerView.ViewHolder {
            TextView tv_question;
            public ViewHolder2(View itemView) {
                super(itemView);
                tv_question = (TextView) itemView.findViewById(R.id.tv_question);
            }
        }

        private class ViewHolder3 extends RecyclerView.ViewHolder {
            TextView tv_question,tv_important;RecyclerView rv_answer;EditText et_score;
            LinearLayout lin_score;
            public ViewHolder3(View itemView) {
                super(itemView);
                tv_question = (TextView) itemView.findViewById(R.id.tv_question);
                tv_important = (TextView) itemView.findViewById(R.id.tv_important);
                rv_answer = (RecyclerView) itemView.findViewById(R.id.rv_answer);
                et_score = (EditText) itemView.findViewById(R.id.et_score);
                lin_score = (LinearLayout) itemView.findViewById(R.id.lin_score);
            }
        }
    }
    public class ChoiceAdapter extends RecyclerView.Adapter<ChoiceAdapter.ViewHolder> {
        private List<GradeQuestionOptionVo> gradeQuestionOptionVoList;private GradeQuestionBankVo gradeQuestionBankVo;
        private int checkPosition=-1;private EditText et_score;
        public ChoiceAdapter(GradeQuestionBankVo gradeQuestionBankVo, List<GradeQuestionOptionVo> gradeQuestionOptionVoList,EditText et_score) {
            this.gradeQuestionOptionVoList = gradeQuestionOptionVoList;
            this.gradeQuestionBankVo = gradeQuestionBankVo;
            this.et_score = et_score;
        }
        @Override
        public ChoiceAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_enforce_basis, parent, false);
            ChoiceAdapter.ViewHolder viewHolder = new ChoiceAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull ChoiceAdapter.ViewHolder holder, int position) {
            holder.rb_radio.setText(gradeQuestionOptionVoList.get(position).getOptionName());
            if(StringUtil.isNullOrEmpty(gradeQuestionBankVo.getBankOptionId())){
                if("1".equals(gradeQuestionOptionVoList.get(position).getDefaultItem())){
                    checkPosition=position;
                    gradeQuestionBankVo.setBankOptionId(gradeQuestionOptionVoList.get(position).getId());//选项的id，根据这个值判断是否已经选择选项
                    setIsFaultiness(gradeQuestionBankVo,gradeQuestionOptionVoList.get(position));
                }
            }else{
                if(gradeQuestionBankVo.getBankOptionId().equals(gradeQuestionOptionVoList.get(position).getId())){
                    checkPosition=position;
                    gradeQuestionBankVo.setBankOptionId(gradeQuestionOptionVoList.get(position).getId());//选项的id，根据这个值判断是否已经选择选项
                    setIsFaultiness(gradeQuestionBankVo,gradeQuestionOptionVoList.get(position));
                }
            }
            holder.rb_radio.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    checkPosition=position;
                    notifyDataSetChanged();
                    gradeQuestionBankVo.setBankOptionId(gradeQuestionOptionVoList.get(position).getId());//选项的id，根据这个值判断是否已经选择选项
                    setIsFaultiness(gradeQuestionBankVo,gradeQuestionOptionVoList.get(position));
                    if(gradeQuestionBankVo.getIsCrux().equals("0")&&(!("合理缺项".equals(gradeQuestionOptionVoList.get(position).getOptionName())||"合格".equals(gradeQuestionOptionVoList.get(position).getOptionName())||"是".equals(gradeQuestionOptionVoList.get(position).getOptionName())))){
                        TextDialog.showScore(context,et_score,gradeQuestionBankVo);
                    }
                }
            });
            if(position==checkPosition){
                holder.rb_radio.setChecked(true);
            }else{
                holder.rb_radio.setChecked(false);
            }
        }

        @Override
        public int getItemCount() {
            return gradeQuestionOptionVoList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            RadioButton rb_radio;
            public ViewHolder(View itemView) {
                super(itemView);
                this.rb_radio = itemView.findViewById(R.id.rb_radio);
            }
        }
    }

    private void setIsFaultiness(GradeQuestionBankVo gradeQuestionBankVo,GradeQuestionOptionVo gradeQuestionOptionVo){
        if("合理缺项".equals(gradeQuestionOptionVo.getOptionName())){
            gradeQuestionBankVo.setIsFaultiness("1");
        }else{
            gradeQuestionBankVo.setIsFaultiness("0");
        }
    }
}